package gofish.servlets;

import java.io.*;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

import gofish.dao.DAOException;
import gofish.dao.GoFishDAOHandler;
import gofish.json.JsonObject;

/**
 * Refresh will be a Servlet that Adam's client code can contact. A client
 * contacts this Servlet probably about once a second until the game ends.
 * 
 * @author Matt Lauber
 */
public class Refresh extends HttpServlet {

	/**
	 * doPost() simply gets the eid_diff from Kylyn's code and returns the
	 * response to the client as a JSON. The eid_diff will be the difference
	 * between the client's current value for eid and the game's actual eid.
	 * Three cases: - If the difference is 0, the client already has the latest
	 * information and does not need to do anything. - If the difference is
	 * positive, the client needs to call GetGameState to get the latest
	 * information. - If the difference is negative, the game's eid has been set
	 * back to -1 to mark that the game is over. The client will then call
	 * GetGameState one last time to find out the game's outcome.
	 * 
	 * This returns a JSON in the following format:
	 * 
	 * { "eid_diff" : int difference }
	 * 
	 * 
	 * @param gid
	 *            - the game the client is currently involved in
	 * @param eid
	 *            - the client's current eid value
	 * @throws IOException
	 */
	@Override
	// public int doPost(int gid, int eid) {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		try {
			JsonObject jsonResponse = new JsonObject();
			String strEid = request.getParameter("eid");
			String strGid = request.getParameter("gid");

				int eid = Integer.parseInt(strEid);
				int gid = Integer.parseInt(strGid);
				// Integer eid_dif = new Integer(GameData.refresh(gid, eid));

				GoFishDAOHandler handler = new GoFishDAOHandler(getServletContext());
				int eid_dif = handler.getEventID(gid) - eid;

				jsonResponse.add("eid_dif", eid_dif);
			out.print(jsonResponse.toString());
		} catch (Exception e) {
			JsonObject json = new JsonObject();
			StringBuilder builder = new StringBuilder();
			builder.append(e.getMessage() + " ");
			for (StackTraceElement elem : e.getStackTrace()) {
				builder.append(elem.toString() + " ");
			}
			json.add("error", builder.toString());
			out.print(json.toString());
		}

		out.flush();
	}
}
